package com.qf.fmall2202.config.websocket;

import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;

@Component
@ServerEndpoint("/webSocket/{oid}")
public class WebSocketServer {

    public static HashMap<String, Session> orderIdSessionMap = new HashMap<>();

    @OnOpen
    public void onOpen(@PathParam("oid") String oid,Session session){

        orderIdSessionMap.put(oid,session);
    }

    @OnClose
    public void onColose(@PathParam("oid") String oid) throws IOException {
        Session session = orderIdSessionMap.get(oid);

        session.close();

        orderIdSessionMap.remove(oid);

    }

    /**
     * 推送消息的静态方法
     * @param oid 订单编号
     * @param msg 要推送的消息
     */
    public static void sendMsg(String oid,String msg) throws IOException {

        Session session = orderIdSessionMap.get(oid);
        session.getBasicRemote().sendText(msg);
    }
}
